package main

import (
	"fmt"
	"gateway/src/common"
	"gateway/src/specialHandle"

	//点代表全部引入 //加_代表强制引入
	"log"
	"net/http"
)

type ProxyHandler struct{}
type mapInterface map[string]interface{}

func (*ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	//defer延迟函数，go会把该段代码压入栈中，待该函数返回前再自动执行
	defer func() {
		if err := recover(); err != nil {
			//设置Header
			w.WriteHeader(500)
			log.Println(err)
		}
	}()
	//动态配置
	test2(w, r)

}
func main() {
	fmt.Println("ok")
	http.ListenAndServe(":9999", &ProxyHandler{})

}
func test2(w http.ResponseWriter, r *http.Request) {
	specialHandle.AddWebFilterFunc(F1, F2, F3)
	//启动过滤链
	specialHandle.StartWebFilter(w, r)
}

// F1 类似这样就可以在各个地方添加过滤器/责任链了
func F1(ctx *specialHandle.MyContext, w http.ResponseWriter, r *http.Request) {

	ctx.KeyValue["key"] = true
}

func F2(ctx *specialHandle.MyContext, w http.ResponseWriter, r *http.Request) {
	data := make(mapInterface) //只能这样处理，否则会报panic: assignment to entry in nil map
	/*data["test1"]="test1"
	data["test2"]="test2"*/

	w.WriteHeader(502)
	_, err := w.Write(common.Fail(data, "权限不足"))
	if err != nil {
		log.Panicln(err)
	}
	ctx.KeyValue["key"] = false
}

func F3(ctx *specialHandle.MyContext, w http.ResponseWriter, r *http.Request) {
	ctx.KeyValue["key"] = false
}
